function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

$(function () {
    console.log("ready!");
});

var app = angular.module('deepDRapp', ['ngRoute']);
// Define the `PhoneListController` controller on the `phonecatApp` module
app.controller('appController', ['$scope', '$timeout', '$http', function appController($scope, $timeout, $http) {
        var getInitAnno = function () {
            return {
                'lesionArr': [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],[0, 0, 0, 0]],
                'clearCurrent': 4,
                'positionCurrent': 5,
                'artifactCurrent': 0,
                'artifactTypeCurrent': [0, 0, 0, 0, 0]
            }
        };

        $scope.name = 'default name2';
        $scope.menuItem = 'anno';
        $scope.debug = false;
        $scope.token = '';
        $scope.LogedIn = false;

        $scope.usrname = '';
        $scope.psw = '';

        $scope.doneList = [];
        $scope.sessions = [];
        $scope.currentImg = 0;
        $scope.currentAnno = [getInitAnno()];
        $scope.CacheNum = 10;
        console.log($scope.sessions);

        $scope.nextImg = function (delta) {
            var target = delta + $scope.currentImg;
            if (target <= 0) {
                target = 0;
            }
            if (target >= $scope.sessions[0].Images.length) {
                target = $scope.sessions[0].Images.length - 1;
            }
            while ($scope.currentAnno.length <= target) {
                $scope.currentAnno.push(JSON.parse(JSON.stringify($scope.currentAnno[$scope.currentAnno.length - 1])));
            }
            $scope.currentImg = target;
            console.log("change to ", target);
        };

        var encodeItem = function (id, score, desp) {
            return {
                id: id,
                score: score,
                desp: desp
            };
        };

        $scope.clearList = [
            encodeItem(1, 1, '只能识别1级血管拱'),
            encodeItem(2, 4, '能识别2级血管拱及小部分病变'),
            encodeItem(3, 6, '识别3级血管拱及部分病变'),
            encodeItem(4, 8, '识别3级血管拱及大部分病变'),
            encodeItem(5, 10, '识别3级血管拱及全部病变')
        ];
        $scope.clearChange = function (i) {
            $scope.currentAnno[$scope.currentImg].clearCurrent = i;
        };

        $scope.positionList = [
            encodeItem(1, 1, '无视盘或黄斑'),
            encodeItem(2, 4, '只有视盘或黄斑'),
            encodeItem(3, 6, '包含视盘和黄斑区'),
            encodeItem(4, 8, '包含视盘和黄斑区及后极部血管拱约后极部 45°'),
            encodeItem(5, 10, '包含视盘和黄斑区及后极部血管拱约后极部 45°+正位')
        ];
        $scope.positionChange = function (i) {
            $scope.currentAnno[$scope.currentImg].positionCurrent = i;
        };

        $scope.artifactList = [
            encodeItem(0, 0, '无伪影'),
            encodeItem(1, -1, '后极血管拱以外，范围小于1/4'),
            encodeItem(2, -4, '影响黄斑区，范围小于1/4'),
            encodeItem(3, -6, '遮盖范围大于1/4，小于1/2'),
            encodeItem(4, -8, '遮盖范围大于1/2，但未全遮盖后极部'),
            encodeItem(5, -10, '遮蔽整个后极部')
        ];
        $scope.artifactChange = function (i) {
            $scope.currentAnno[$scope.currentImg].artifactCurrent = i;
        };

        $scope.artifactTypeList = [
            encodeItem(1, 0, '照相机光学系 统污迹或污斑'),
            encodeItem(2, 0, '睫毛或睫毛异物虚影'),
            encodeItem(3, 0, '像周边区黄色边缘'),
            encodeItem(4, 0, '眼底像总体模糊 、暗'),
            encodeItem(5, 0, '黄斑区暗影')
        ];
        $scope.artifactTypeCurrent = 1;
        $scope.artifactTypeChange = function (i) {
            $scope.currentAnno[$scope.currentImg].artifactTypeCurrent[i] =
                1 - $scope.currentAnno[$scope.currentImg].artifactTypeCurrent[i];
        };

        $scope.scoreDesp = [
            '能识别3级血管拱及部分病变，位置包含视盘和黄斑区，结果可信程度较差。',
            '清晰度能识别3级血管拱及部分病变，位置包含视盘和黄斑区。能反应包含视盘和黄斑区的部分病变，结果一般。',
            '清晰度能眼底照相能识别3级血管拱及大部分病变，位置能包含视盘和黄斑区及后极部血管拱，可能有后极血管拱以外，范围小于1/4的伪影。能反应包含视盘和黄斑区及后极部 45°范围的大部分病变，结果可信程度高。',
            '位置能包含视盘和黄斑区及后极部血管拱约后极部 45°，清晰度能眼底照相能识别3级血管拱及大部分病变或全部病变，可能有后极血管拱以外，范围小于1/4的伪影。能反应包含视盘和黄斑区及后极部 45°范围的大部分病变，结果可信程度高。'
        ];
        $scope.scoreShortDesp = [
            '差,无法判定',
            '一般,可以判定',
            '良好,可以判定，结果可信',
            '优秀,判定结果可靠'
        ];
        $scope.despCurrent = 3;
        $scope.scoreCurrent = 20;
        $scope.$watch('currentAnno',
            function (newvals, oldvals, scope) {
                console.log("change");
                $scope.scoreCurrent = $scope.clearList[$scope.currentAnno[$scope.currentImg].clearCurrent - 1].score +
                    $scope.positionList[$scope.currentAnno[$scope.currentImg].positionCurrent - 1].score +
                    $scope.artifactList[$scope.currentAnno[$scope.currentImg].artifactCurrent].score;
                if ($scope.scoreCurrent < 11) {
                    $scope.despCurrent = 0;
                } else if ($scope.scoreCurrent < 15) {
                    $scope.despCurrent = 1;
                } else if ($scope.scoreCurrent < 17) {
                    $scope.despCurrent = 2;
                } else {
                    $scope.despCurrent = 3;
                }
            },
            true
        );


        $scope.set_token = function (token) {
            $scope.token = token;
            setCookie('token', token, 7);
        };
        $scope.set_menu_item = function (manu_item) {
            $scope.menuItem = manu_item;
            if (manu_item == 'list') {
                $scope.getDoneList();
            }
            console.log("Error Menu")
        };
        $scope.init = function () {
            console.log('init');
            tk = getCookie('token');
            if (tk !== '') {
                $scope.token = tk;
                $scope.LogedIn = true;
            }
            console.log(tk);
            $scope.set_menu_item('anno');
            $scope.HandleImglist()
        };
        $scope.login = function () {
            $http({
                method: 'POST',
                url: '/api/get_token',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: {
                    'user_name': $scope.usrname,
                    'password': $scope.psw
                }
            }).then(function (response) {
                // success call back
                console.log('successful request');
                console.log(JSON.stringify(response.data));
                if (response.data['token'] !== '') {
                    $scope.set_token(response.data['token']);
                    succ = true;
                    $scope.LogedIn = true;
                    $scope.HandleImglist();
                } else {
                    console.log(response.data)
                }
            }, function (response) {
                console.log(response)
            });

        };

        $scope.getSession = function (sessionObj) {
            console.log('gerting session ', sessionObj.Id);
            var url = "/api/get_session";
            $http({
                method: 'POST',
                transformResponse: null,
                url: url,
                headers: {
                    'token': $scope.token
                },
                data: sessionObj
            }).then(function (response) {
                // success call back
                // console.log("Get Session::", response.data);
                obj = JSON.parse(response.data);
                // for (var i = 0; i < obj.Images.length; i+=1){
                // obj.Images[i].Annotation = getInitAnno();
                // }
                $scope.sessions.push(obj);
                console.log("Succ get ", obj.Id);
                // console.log($scope.sessions)
            }, function (response) {
                console.log(response)
            });
        };

        $scope.HandleImglist = function () {
            data = {
                "offset": $scope.sessions.length,
                "limit": $scope.CacheNum - $scope.sessions.length
            };
            $http({
                method: 'POST',
                url: '/api/get_list',
                headers: {
                    'token': $scope.token,
                    'Content-Type': 'application/json'
                },
                data: data
            }).then(function (response) {
                // success call back
                console.log('Add imglist succ');
                // console.log(response.data);
                //TODO get data here
                for (var i = 0; i < response.data.Sessions.length; i++) {
                    $scope.getSession(response.data.Sessions[i])
                }
            }, function (response) {
                console.log(response)
            });
        };
        $scope._barrier = [];
        $scope.submitAndNext = function () {
            console.log('Add Annotate');
            if ($scope.currentAnno.length < $scope.sessions[0].Images.length) {
                alert("请完成该病人完成所有图片标记再提交。");
                return;
            }

            function bin2dec(arr) {
                result = 0;
                for (var i = arr.length - 1; i >= 0; i -= 1) {
                    result *= 2;
                    if (arr[i]) {
                        result += 1;
                    }
                }
                return result;
            }

            var annotations = $scope.currentAnno;
            var submitSession = $scope.sessions.shift();
            $scope.currentImg = 0;
            $scope.currentAnno = [getInitAnno()];
            for (var i = 0; i < submitSession.Images.length; i++) {
                data = {
                    'Image': submitSession.Images[i].Id,
                    'Lesion_ha': bin2dec(annotations[i].lesionArr[2]),
                    'Lesion_sex': bin2dec(annotations[i].lesionArr[0]),
                    'Lesion_hex': bin2dec(annotations[i].lesionArr[1]),
                    'Lesion_ma': bin2dec(annotations[i].lesionArr[3]),
                    'Lesion_va': bin2dec(annotations[i].lesionArr[4]),
                    'Level': annotations[i].level,
                    'Artifact': annotations[i].artifactCurrent,
                    'ArtifactType': bin2dec(annotations[i].artifactTypeCurrent),
                    'Clear': annotations[i].clearCurrent,
                    'Position': annotations[i].positionCurrent
                };
                $scope._barrier.push(i);
                $http({
                    method: 'POST',
                    url: '/api/add_annotation',
                    headers: {
                        'token': $scope.token,
                        'Content-Type': 'application/json'
                    },
                    data: data
                }).then(function (response) {
                    // success call back
                    console.log('Add Anno succ');
                    $scope._barrier.pop();
                }, function (response) {
                    console.log(response)
                });
            }

            var timeout = setInterval(function () {
                if ($scope._barrier.length === 0) {
                    clearInterval(timeout);
                    console.log("###Call get list");
                    $scope.HandleImglist();
                }
            }, 10);
        };
        $scope.getDoneList = function () {
            console.log('Get Done List');
            var req = $http({
                method: 'GET',
                url: '/api/get_done',
                headers: {
                    'token': $scope.token
                }
            }).then(function (response) {
                // success call back
                console.log('Get Done List Succ');
                console.log(response);
                $scope.doneList = response.data;
            }, function (response) {
                console.log(response)
            });
            console.log(req)
        }
    }]
);

